<template>
    <div style="height: 750px;overflow-y: auto;padding: 10px" ref="scrollContainer">
        <ReportComparisonSearch @search="handleSearch" :type="JSON.parse(content.stepDetail).engineType"
            :step-id="content.id" />
        <Card title="前5条step配置" :bordered="false" style="width: 100%">
            <!-- :scroll="{ x: 2000 }" -->
            <Table :columns="columns" :data-source="historySuccessSteps" :pagination="false">
                <template #bodyCell="{ column, index }">
                    <template v-if="column.key === 'action'">
                        <a @click="showHistoryStep(index)">查看</a>
                    </template>
                </template>

            </Table>
        </Card>
        <div flex="~ justify-between" style="margin-top: 20px;">
            <Card title="当前配置" :bordered="false" style="width: 48%">
                <ApiCaseStep :operator-disabled="true" :selected-step="JSON.parse(content.stepDetail)"
                    :differentFields="historySuccessSteps?.[showHistoryStepIndex]?.['differentFields'] ?? []"
                    v-if="JSON.parse(content.stepDetail).type === 'API'"></ApiCaseStep>
                <UiDatabaseStep :operator-disabled="true" :selected-step="JSON.parse(content.stepDetail)"
                    :differentFields="historySuccessSteps?.[showHistoryStepIndex]?.['differentFields'] ?? []"
                    v-if="JSON.parse(content.stepDetail).type === 'DATABASE'" />
                <UiCaseStep :operator-disabled="true" :selected-step="JSON.parse(content.stepDetail)"
                    :differentFields="historySuccessSteps?.[showHistoryStepIndex]?.['differentFields'] ?? []" :data="data"
                    v-if="JSON.parse(content.stepDetail).type === 'UI'" />
            </Card>
            <Card :title="`第${showHistoryStepIndex + 1}条配置`" :bordered="false" style="width: 48%">
                <ApiCaseStep :operator-disabled="true" :selected-step="historySuccessSteps?.[showHistoryStepIndex] ?? {}"
                    :differentFields="historySuccessSteps?.[showHistoryStepIndex]?.['differentFields'] ?? []"
                    v-if="JSON.parse(content.stepDetail).type === 'API'" />
                <UiDatabaseStep :operator-disabled="true" :selected-step="historySuccessSteps?.[showHistoryStepIndex] ?? {}"
                    :differentFields="historySuccessSteps?.[showHistoryStepIndex]?.['differentFields'] ?? []"
                    v-if="JSON.parse(content.stepDetail).type === 'DATABASE'" />
                <UiCaseStep :operator-disabled="true" :selected-step="historySuccessSteps?.[showHistoryStepIndex] ?? {id: ''}"
                    :data="data" :differentFields="historySuccessSteps?.[showHistoryStepIndex]?.['differentFields'] ?? []"
                    v-if="JSON.parse(content.stepDetail).type === 'UI'" />
            </Card>
        </div>
    </div>
</template>


<script setup lang="ts">
import { Card, Table } from 'ant-design-vue';
import type { ColumnsType } from 'ant-design-vue/es/table'
import type { IBasicWithPage } from '~/types/apis/basic'
import type { AfterFetchContext } from '@vueuse/core'
import type { IReportSearch, IReportHistory } from '~/types/apis/report'
import type { IBasic } from '~/types/apis/basic'

const scrollContainer: globalThis.Ref = ref();

defineProps<{
    pageType?: string
}>()

const content = defineModel<any>('content', {
    required: true,
})

const columns: ColumnsType<any> = [
    {
        title: '序号',
        dataIndex: 'id',
        key: 'id',
        fixed: 'left',
        align: 'center',
        width: 80
    },
    { title: '排序', dataIndex: 'num', key: 'num', align: 'center', width: 80 },
    { title: '名称', dataIndex: 'name', key: 'name', align: 'center' },
    {
        title: '描述',
        dataIndex: 'description',
        key: 'description',
        align: 'center',
        width: 100
    },
    { title: '路径', dataIndex: 'path', key: 'path', align: 'center', width: 300, ellipsis: true },
    {
        title: '环境 ID',
        dataIndex: 'environmentId',
        key: 'environmentId',
        align: 'center',
    },
    { title: '请求类型', dataIndex: 'method', key: 'method', align: 'center', width: 100 },
    {
        title: '修改时间',
        dataIndex: 'gmtModified',
        key: 'gmtModified',
        width: 200,
        align: 'center',
    },
    {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
        fixed: 'right',
        width: 170,
        align: 'center',
    },
]

// 默认查看第一个历史步骤
const showHistoryStepIndex = ref(0)

const fetchData: IReportSearch = reactive({
    // 用例id
    caseId: content.value.caseId,
    // 执行状态(恒为true)
    executeState: content.value.executeState,
    // 断言状态(恒为true)
    assertionState: content.value.assertionState,
    // 步骤详情
    stepDetail: JSON.parse(content.value.stepDetail),
    // 步骤名称
    name: '',
    // 步骤ID（步骤详情中的id）
    caseStepId: '',
})


// 根据step类型向接口参数传可选参数  以下参数都为可选参数
watch(content, async (step: IReportHistory) => {
    const type = JSON.parse(step.stepDetail).engineType;
    fetchData.caseStepId = ''
    fetchData.name = ''
    if (type === 'API' || type === 'MIX') {
        fetchData.path = ''
        fetchData.method = ''
    }
    if (type === 'UI' || type === 'MIX') {
        fetchData.operationType = ''
        fetchData.locationType = ''
        fetchData.locationExpress = ''
    }



    showHistoryStepIndex.value = 0
    await nextTick()
    // 当页面重新打开时，保留了上一次页面滚动位置，需要重置
    if (scrollContainer.value.scrollTop > 0) {
        scrollContainer.value.scrollTop = 0;
    }
    fetchData.stepDetail = JSON.parse(step.stepDetail)
    if (JSON.parse(step.stepDetail).type === 'UI') {
        await  getDictList()
    }
    fetchHistorySuccess(fetchData).execute()
   
}, { immediate: true, deep: true })


// 根据条件搜索历史步骤
const handleSearch = (searchParams: IReportSearch) => {
    for (const key in searchParams) {
        if (Object.prototype.hasOwnProperty.call(searchParams, key)) {
            // 勾选相关条件后，动态向搜索参数中添加数据
            const element = searchParams[key as keyof IReportSearch];
            if (element !== undefined) {
                if (key in fetchData) {
                    if (element) {
                        if (key === 'caseStepId') {
                            fetchData[key as keyof typeof fetchData] = JSON.parse(content.value.stepDetail).id
                        } else {
                            fetchData[key as keyof typeof fetchData] = content.value[key as keyof typeof fetchData];
                        }
                    } else {
                        fetchData[key as keyof typeof fetchData] = '' as never;
                    }
                }
            }
        }
    }
    // 获取条件查询数据
    fetchHistorySuccess(fetchData).execute()
}

// 根据step的类型判断接口名称
const fetchHistorySuccessUrl = computed(() => {
    const engineType = JSON.parse(content.value.stepDetail).engineType;
    if (engineType === 'API') {
        return `/data-service/api/v1/contrast/selectHistorySuccessStepApi`
    } else if (engineType === 'UI') {
        return `/data-service/api/v1/contrast/selectHistorySuccessStepUi`
    } else if (engineType === 'MIX') {
        return `/data-service/api/v1/contrast/selectHistorySuccessStepMix`
    }
    return ''
})

// 请求历史步骤数据
const {
    data: historySuccessSteps,
    post: fetchHistorySuccess,
    isFetching,
} = useCustomFetch<IReportHistory[]>(fetchHistorySuccessUrl, {
    immediate: false,
    initialData: [],
    afterFetch: (ctx: AfterFetchContext<IBasicWithPage<IReportHistory>>) => {
        if (ctx.data && ctx.data.code === 0) {
            return {
                data: ctx.data.data,
                response: ctx.response,
            }
        }
        return {
            data: [],
            response: ctx.response,
        }
    },
})

// 查看历史步骤详情
const showHistoryStep = (index: number) => {
    showHistoryStepIndex.value = index
}


const { data, post: getDictList } = useCustomFetch<ResponseType>(
    '/engine-service/api/v1/dict/list?category=ui_location_type,browser,mouse,keyboard,wait,assertion,img,browser_type,combination, select, iframe',
    {
        initialData: {},
        afterFetch(ctx: AfterFetchContext<IBasic<ResponseType>>) {
            if (ctx.data && ctx.data.code === 0) {
                return {
                    data: ctx.data.data,
                    response: ctx.response,
                }
            }
            return {
                data: [],
                response: ctx.response,
            }
        },
    },
)

</script>

<style scoped>
::-webkit-scrollbar {
    border: none;
}
</style>